import logging
from forest.api import Command, get_tool

import os.path
logger = logging.getLogger('forest.commands.SSH')

from collections import OrderedDict

class SSHKeys(Command):
    ''' Sets up ssh keys in the target following their resource specification.

    '''
    __register__ = 'commands.setup.SSHKeys'

    requires_config = ['ssh']

    def run(self, config):
        authorized_keys = config.join_install_root('root', '.ssh', 'authorized_keys')

        authorized_keys_map = OrderedDict()

        if os.path.exists(authorized_keys):

            lines = open(authorized_keys, 'r').readlines()
            for line in lines:
                type, key, host = line.strip().split(' ')
                authorized_keys_map[host] = (type, key)

        for key in config.get_resources().iter_by_type('ssh-key'):
            if not key.get_installed() and key.get_host() in  authorized_keys_map:
                del authorized_keys_map[key.get_host()]
                continue

            if not key.get_installed():
                continue

            authorized_keys_map[key.get_host()] = (key.get_type(), key.get_key())

        string = []
        for host, (type, key) in authorized_keys_map.iteritems():
            string.append('%s %s %s' % (type, key, host))

        get_tool('files.write')(authorized_keys, '\n'.join(string))


